<template>
  <div class="pre-code">
    <div class="error-detail">
      <pre class="error-code" v-html="computedLine"></pre>
    </div>
    <p></p>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { useSourcemapInfo } from '../../stores/sourcemapInfo';
import { isEmpty } from 'lodash-es';

const { getSourcemapInfo } = useSourcemapInfo();

const encodeHTML = (str) => {
  if (!str || !str.length) return '';
  return str
    .replace(/&/g, '&#38;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/'/, '&#39;');
};

const computedLine = computed(() => {
  if (isEmpty(getSourcemapInfo())) return '';
  const line = getSourcemapInfo().line;
  const originCodeLine = getSourcemapInfo().code.split('\n');
  const len = originCodeLine.length - 1;
  const start = line - 3 >= 0 ? line - 3 : 0;
  // 最多展示6行
  const end = start + 5 >= len ? len : start + 5;

  return getPreLine(start, end, originCodeLine, line);
});

const getPreLine = (start, end, originCodeLine, line) => {
  const newLines = [];

  for (let i = start; i <= end; ++i) {
    const content = `${i + 1}.  ${encodeHTML(originCodeLine[i])}`;
    newLines.push(
      `<div class='code-line ${
        i + 1 === line ? 'heightlight' : ''
      }'>${content}</div>`
    );
  }
  return newLines.join('');
};
</script>

<style scoped lang="less">
.pre-code {
  .error-detail {
    .error-code {
      padding: 10px;
      overflow: hidden;
      word-wrap: normal;
    }
  }

  .code-line {
    padding: 4px;
  }

  .heightlight {
    color: #fff;
    background-color: red;
  }
}
</style>
